﻿using PCControlService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PCControlCommand
{
    public partial class Form1 : Form
    {
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
        bool connecting = false;
        delegate void DoSomething();
        private Dictionary<string, DoSomething> CMDList = new Dictionary<string, DoSomething>();
        public Form1()
        {
            InitializeComponent();
            CMDList.Add("播放/暂停", delegate { TisnControl.SendKey(Keys.MediaPlayPause); });
            CMDList.Add("停止", delegate { TisnControl.SendKey(Keys.MediaStop); });
            CMDList.Add("上一曲", delegate { TisnControl.SendKey(Keys.MediaPreviousTrack); });
            CMDList.Add("下一曲", delegate { TisnControl.SendKey(Keys.MediaNextTrack); });
            CMDList.Add("音量+", delegate { TisnControl.SendKey(Keys.VolumeUp); });
            CMDList.Add("音量-", delegate { TisnControl.SendKey(Keys.VolumeDown); });
            CMDList.Add("静音", delegate { TisnControl.SendKey(Keys.VolumeMute); });
            CMDList.Add("关机", delegate { TisnControl.DoExitWin(); });
        }
        #region Udp连接方式
        private bool udpConnecting = true;
        /// <summary>
        /// Udp连接方式
        /// </summary>
        /// <param name="serverIP"></param>
        public void UdpServer(IPEndPoint serverIP)
        {
            Log("UDP服务器开始监听" + serverIP.Port + "端口");
            Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(serverIP);
            udpServer.ReceiveTimeout = 2000;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)ipep;
            new Thread(() =>
            {
                while (udpConnecting)
                {
                    byte[] data = new byte[1024];
                    int length = 0;
                    try
                    {
                        length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
                    }
                    catch (Exception ex)
                    {
                        //Log(string.Format("出现异常：{0}", ex.Message));
                        //Thread.Sleep(500);
                        continue;
                    }
                    string datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string message = Encoding.UTF8.GetString(data, 0, length);
                    string ipport = (Remote as IPEndPoint).Address.ToString() + ":" + (Remote as IPEndPoint).Port.ToString();
                    Log(string.Format("{0} 收到来自{1}的消息：{2}", datetime, ipport, message));
                    if (message.Equals("01握手"))
                    {
                        Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        byte[] d = Encoding.UTF8.GetBytes("02握手");
                        IPEndPoint ip = new IPEndPoint((Remote as IPEndPoint).Address, 5678);
                        udpClient.SendTo(d, ip);
                        udpClient.Close();
                    }
                }
                udpServer.Close();
            }).Start();
        }
        #endregion

        #region "TCP连接"
        Socket serverSocket;
        private void TCPServer()
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var ip = "0.0.0.0";
            Log("IP:" + ip);
            serverSocket.Bind(new IPEndPoint(IPAddress.Parse(ip), 5317));  //绑定IP地址：端口  
            serverSocket.Listen(10);//设定最多10个排队连接请求 
            new Thread(ListenClientConnect).Start(serverSocket);
        }
        private void ListenClientConnect(object server)
        {
            Socket serverSocket = (Socket)server;
            while (connecting)
            {
                try
                {
                    var clientSocket = serverSocket.Accept();//线程在此等待，直到有客户端连接后方继续执行
                    clientSocket.Send(Encoding.UTF8.GetBytes("mm密钥"));
                    Thread receiveThread = new Thread(ReceiveMsg);//启动接收信息线程
                    receiveThread.Start(clientSocket);
                }
                catch { }
            }
        }
        /// <summary>
        /// 接受消息处理线程
        /// </summary>
        /// <param name="clientForm"></param>
        public void ReceiveMsg(object clientForm)
        {
            Socket myClient = (Socket)clientForm;
            myClient.ReceiveTimeout = 2000;
            byte[] result = new byte[1024];
            while (connecting)
            {

                try
                {
                    Thread.Sleep(500);
                    //通过clientSocket接收数据  
                    int receiveLength = myClient.Receive(result);
                    if (receiveLength <= 0)
                    {
                        //Log("断开连接");
                        continue;
                    }
                    string resultStr = Encoding.UTF8.GetString(result, 0, receiveLength - 1);
                    var header = resultStr.Substring(0, 2);
                    string content = "";
                    content = resultStr.Substring(2, resultStr.Length - 2);
                    switch (header)
                    {
                        case "yz":
                            myClient.Send(Encoding.UTF8.GetBytes("yz通过"));
                            break;
                        case "ml":
                            Log("执行命令：" + content);
                            if (CMDList.ContainsKey(content))
                            {
                                CMDList[content]();
                            }
                            myClient.Send(Encoding.UTF8.GetBytes(resultStr));
                            break;
                        case "dc":
                            connecting = false;

                            break;
                    }
                }
                catch (Exception e)
                {
                }
            }
            myClient.Close();
        }


        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        private string GetAddressIP()
        {
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }

        /// <summary>
        /// 获取本机物理网卡的ip
        /// </summary>
        /// <returns></returns>
        public static string GetIPAddress()
        {
            string userIP = "";
            System.Net.NetworkInformation.NetworkInterface[] fNetworkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            foreach (System.Net.NetworkInformation.NetworkInterface adapter in fNetworkInterfaces)
            {
                string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
                Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
                if (rk != null)
                {
                    // 区分 PnpInstanceID      
                    // 如果前面有 PCI 就是本机的真实网卡          
                    string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                    int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
                    if (fPnpInstanceID.Length > 3 &&
                    fPnpInstanceID.Substring(0, 3) == "PCI")
                    {
                        //string fCardType = "物理网卡";
                        System.Net.NetworkInformation.IPInterfaceProperties fIPInterfaceProperties = adapter.GetIPProperties();
                        System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = fIPInterfaceProperties.UnicastAddresses;
                        foreach (System.Net.NetworkInformation.UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection)
                        {
                            if (UnicastIPAddressInformation.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                userIP = UnicastIPAddressInformation.Address.ToString(); // Ip 地址     
                        }
                        break;
                    }

                }
            }
            return userIP;
        }

        public string GetLocalIP()
        {
            IPAddress localIp = null;
            try
            {
                IPAddress[] ipArray;
                ipArray = Dns.GetHostAddresses(Dns.GetHostName());
                localIp = ipArray.First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.StackTrace + "\r\n" + ex.Message, "错误", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                //Log.WriteLog(ex);
            }
            if (localIp == null)
            {
                localIp = IPAddress.Parse("127.0.0.1");
            }
            return localIp.ToString();
        }

        #endregion
        const int WM_PCCONTROL = 5317520;
        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_PCCONTROL:
                    COPYDATASTRUCT cds = new COPYDATASTRUCT();
                    Type t = cds.GetType();
                    cds = (COPYDATASTRUCT)m.GetLParam(t);
                    string strResult = cds.dwData.ToString() + ":" + cds.lpData;

                    listBox1.Items.Add(cds.lpData);
                    switch (cds.lpData)
                    {
                        case "Close":
                            Close();
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }
        private void Log(string message)
        {
            Debug.WriteLine(message);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.ShowInTaskbar = false;
            this.WindowState = FormWindowState.Minimized;
            connecting = true;
            UdpServer(new IPEndPoint(IPAddress.Any, 6789));
            Log("服务启动");
            TCPServer();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            connecting = false;
            udpConnecting = false;
            if (serverSocket != null)
                serverSocket.Close();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
